import axios from 'axios';
import { Message, MessageBox } from 'element-ui';
import { getToken } from './auth';
import router from '@/router';
import setting from '@/settings.js';
import store from '../store';
const http = axios.create({
  baseURL: '',
  timeout: 30000
});

// request 拦截器
http.interceptors.request.use(
  config => {
    const token = getToken();
    if (token) {
      config.headers = Object.assign(config.headers || {}, {
        [setting.jwtHeader]: token
      });
    } else {
      router.replace({
        path: '/login',
        query: {
          redirect: router.currentRoute.fullPath
        }
      });
    }
    return config;
  },
  error => {
    Message.error({ message: '请求超时!' });
    return Promise.reject(error);
  }
);

http.interceptors.response.use(
  res => {
    const response = res.data;
    if (response.code === 0) {
      return Promise.resolve(response);
    } else if (response.code === 10040010) {
      MessageBox.confirm(
        '用户名或密码错误',
        '系统提示',
        {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'error'
        }
      ).then(() => {
        store.dispatch('user/logout').then(() => {
          location.reload(); // 为了重新实例化vue-router对象 避免bug
        });
      });
      return Promise.reject(response);
    } else if (response.code === 10040009) {
      router.push('/401');
    } else {
      Message.error({
        message: response.message
      });
      throw response.message;
    }
  },
  error => {
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = '请求错误(400)';
          break;
        case 401:
          error.message = '未授权，请重新登录(401)';
          break;
        case 403:
          error.message = '拒绝访问(403)';
          break;
        case 404:
          error.message = '请求出错(404)';
          break;
        case 408:
          error.message = '请求超时(408)';
          break;
        case 500:
          error.message = '服务器错误(500)';
          break;
        case 501:
          error.message = '服务未实现(501)';
          break;
        case 502:
          error.message = '网络错误(502)';
          break;
        case 503:
          error.message = '服务不可用(503)';
          break;
        case 504:
          error.message = '网络超时(504)';
          break;
        case 505:
          error.message = 'HTTP版本不受支持(505)';
          break;
        default:
          error.message = `连接出错(${error.response.status})!`;
      }
    } else {
      console.error(error);
      error.message = '连接服务器失败!';
    }
    Message.error({ message: error.message });
    return Promise.reject(error);
  }
);

export default http;
